package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.mapper.TbOrderRecordMapper;
import com.bwie.mapper.TbProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.*;
import com.bwie.service.IUserService;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtils;
import com.bwie.vo.OrderDetailVo;
import com.bwie.vo.PageInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-06-20 15:27:42
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{


    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    TbOrderRecordMapper tbOrderRecordMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    IUserService userService;

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {

        String token = request.getHeader("token");
        if(token == null) {
            return R.error().setMsg("请先登录");
        }
        Integer userId = TokenUtils.getUserId(token);


        //--1 构造分页参数
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //--2 分页获取订单列表
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();

        // 商品名称/关键字/id模糊查询
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())) {
            wrapper.lambda().like(TbOrder::getProdInfo, pageInfoVo.getKeyWord())
                    .or()
                    .eq(TbOrder::getOrderId, pageInfoVo.getKeyWord());
        }
        // 订单状态精确查询
        if(pageInfoVo.getStatus() != null) {
            wrapper.lambda().eq(TbOrder::getOrderStatus, pageInfoVo.getStatus());
        }
        // 订单类型精确查询
        if(pageInfoVo.getType() != null) {
            wrapper.lambda().eq(TbOrder::getOrderType, pageInfoVo.getType());
        }

        wrapper.lambda().orderByDesc(TbOrder::getOrderId);

        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);

        for (TbOrder record : tbOrderPage.getRecords()) {

            List<String> imagesList = tbOrderMapper.getOrderImageList(record.getOrderId());
            List<String> imageList = new ArrayList<String>();
            if(imagesList != null && imagesList.size() > 0) {
                for (String s : imagesList) {
                    if(s != null) {
                        List<String> list = JSON.parseArray(s, String.class);
                        imageList.addAll(list);
                    }
                }
            }

            record.setImageList(imageList);
        }

        //-- 数据返回之前，把前端显示的列表，存入缓存
        String key = "order-list-" + userId;
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(tbOrderPage.getRecords()));

        return R.ok().setData(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(List<TbProdInfo> infoList) {
        // 通过token，获取当前定的用户ID
        String token = request.getHeader("token");
        if(token == null) {
            return R.error().setMsg("请先登录");
        }
        Integer userId = TokenUtils.getUserId(token);
        String userName = TokenUtils.getUserName(token);

        //--1 检查库存，并扣减库存
        BigDecimal totalAmount = new BigDecimal("0");
        StringBuilder prodNames = new StringBuilder();

        // 获取分布式锁
        RLock lock = redissonClient.getLock("order-lock");

        try {
            // 加锁
            lock.lock();

            for (TbProdInfo tbProdInfo : infoList) {
                TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
                if(tbProdInfo.getBuyNum() > prodInfo.getProdStock()) {
                    throw new RuntimeException("库存不足");
                }

                // 扣减并更新库存
                prodInfo.setProdStock(prodInfo.getProdStock() - tbProdInfo.getBuyNum());
                tbProdInfoMapper.updateById(prodInfo);

                // 计算订单金额
                totalAmount = totalAmount.add(tbProdInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())));

                // 拼接商品名称
                if(prodNames.length() > 0) {
                    prodNames.append(",");
                    prodNames.append(tbProdInfo.getProdName());
                }
                else {
                    prodNames.append(tbProdInfo.getProdName());
                }

            }

        }
        finally {
            // 解锁
            lock.unlock();
        }



        //--2 创建订单
        TbOrder tbOrder = new TbOrder();
        // 雪花算法生成订单编号
        long id = IdUtil.getSnowflake(1, 1).nextId();
        tbOrder.setOrderNo("" + id);

        tbOrder.setOrderType(1);
        tbOrder.setOrderStatus(0);
        tbOrder.setUserId(userId);
        tbOrder.setOrderAmount(totalAmount);
        tbOrder.setProdInfo(prodNames.toString());
        tbOrder.setCreateTime(new Date());
        tbOrder.setCreateBy(userName);

        tbOrderMapper.insert(tbOrder);

        //--3 创建订单明细
        for (TbProdInfo tbProdInfo : infoList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            // 关联订单
            tbOrderDetail.setOrderId(tbOrder.getOrderId());

            tbOrderDetail.setBuyNum(tbProdInfo.getBuyNum());
            tbOrderDetail.setProdId(tbProdInfo.getProdId());
            tbOrderDetail.setBuyPrice(tbProdInfo.getProdPrice());
            tbOrderDetail.setInfoId(tbProdInfo.getInfoId());
            tbOrderDetail.setCreateBy(userName);
            tbOrderDetail.setCreateTime(new Date());

            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        //--4 新增订单记录
        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        tbOrderRecord.setOptRecord("用户创建订单");
        tbOrderRecord.setCreateTime(new Date());
        tbOrderRecord.setCreateBy(userName);

        tbOrderRecordMapper.insert(tbOrderRecord);

        return R.ok();
    }

    @Override
    public void exportOrderList(Integer userId) {


        //--1 创建导出工具
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<>(TbOrder.class);

        //--2 从缓存中获取订单列表
        String key = "order-list-" + userId;
        String s = stringRedisTemplate.opsForValue().get(key);
        List<TbOrder> tbOrderList = JSON.parseArray(s, TbOrder.class);


        //--2 导出excel文件
        excelUtil.exportExcel(response, tbOrderList, "订单列表");
    }

    @Override
    public R getOrderInfoById(Integer orderId) {
        //--1 获取订单信息
        TbOrder tbOrder = tbOrderMapper.selectById(orderId);
        if(tbOrder == null) {
            return R.error().setMsg("订单不存在");
        }

        //--2 获取用户信息（OpenFeign）
        R r = userService.getUserInfoById(tbOrder.getUserId());
        if(r.getCode() != 200) {
            return r;
        }
        String s = JSON.toJSONString(r.getData());
        TbUser tbUser = JSON.parseObject(s, TbUser.class);
        tbOrder.setUser(tbUser);

        //--3 根据订单ID获取商品列表
        List<OrderDetailVo> orderDetailList = tbOrderMapper.getOrderDetailList(orderId);
        tbOrder.setDetailList(orderDetailList);

        //--4 获取订单记录列表
        List<TbOrderRecord> recordList = tbOrderRecordMapper.selectList(
                new QueryWrapper<TbOrderRecord>().lambda()
                        .eq(TbOrderRecord::getOrderId, orderId)         // 订单ID
                        .orderByAsc(TbOrderRecord::getCreateTime)       // 根据创建时间升序排列
        );
        tbOrder.setRecordList(recordList);


        return R.ok().setData(tbOrder);
    }
}




